<?php
// Application core configuration
require_once '../app/configuration/core.php';

// Register autoloader
require_once 'Zend/Loader/Autoloader.php';
$autoloader = Zend_Loader_Autoloader::getInstance();
spl_autoload_register(array($autoloader,'autoload'));

$autoloader->registerNamespace('KontorX');

/**
 * Image resizer .. magick ;) 
 */

/**
 * Filtering route 
 */
$_GET = array_map('urldecode', (array) $_GET);

$path = str_replace('..', '', @$_GET['path']);
$type = basename(@$_GET['type']);
$file = basename(@$_GET['file']);

// Prepare
$basePath = PUBLIC_PATHNAME . '/upload/' . trim($path, '/') . '/';
$filePath = $basePath . $file;
$fileWrite = $type . '/' . $file;

/**
 * Validation 
 */

// Check if file exsists
if (!is_file($filePath)) {
	// image file do not exsists
	header("HTTP/1.0 404 Not Found");
}

/**
 * Init configuration 
 */

$configPath = APP_CONFIGURATION_PATHNAME . 'image.php';
if (!is_file($configPath)) {
	// config file do not exsists
	header("HTTP/1.0 404 Not Found");
	die ('1');
}

$config = require_once APP_CONFIGURATION_PATHNAME . 'image.php';
if (!is_array($config)) {
	// config is not array
	header("HTTP/1.0 404 Not Found");
	die ('2');
}


$resizer = new KontorX_Image_Resizer($config);
$resizer->setDirname($basePath);
$resizer->setFilename($file);
$resizer->setMultiType($type);

try {
	$image = $resizer->resize();
	// display
	$image->display();

	// save
	$write = new KontorX_File_Write($config);
	$write->setBasedir($basePath);
	$write->write($fileWrite, $image->toString());
} catch (Exception $e) {
	header("HTTP/1.0 404 Not Found");
	print $e->getMessage();
}
